"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 夏令时跳转后频繁创建数据库
Create At   : 2021/01/08
@zou_jialiang0505328126
Description :
    1.创建数据库test
    2.创建表空间
    3.设置操作系统时区为new_york
    4、设置操作系统时间为2020-03-08凌晨01:58
    5、反复修改数据库100次
Expect      :
    1.创建数据库成功
    2.创建表空间成功
    3.配置成功
    4.修改时间成功
    5.成功率100%
History     :
    Modified by @wan005 2021/3/23: 增加环境时区修复步骤
"""

import unittest
import time
import datetime
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

new_york_local = '/usr/share/zoneinfo/America/New_York'
ln_sf_cmd = 'ln -sf {zone} /etc/localtime'


class DdlDatabase(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('-------Opengauss_Reliability_Dbsys_Case237.py 开始执行---')
        self.db_primary_db_user = Node(node='PrimaryDbUser')
        self.db_primary_root_node = Node(node='PrimaryRoot')
        self.constant = Constant()
        self.common = Common('PrimaryRoot')
        self.dbname = 'test_db'
        self.dbspace = 'tbspace_case237'

        result = self.common.check_system_timezone(
            *('PrimaryRoot', 'Standby1Root', 'Standby2Root'))
        self.log.info(result)
        self.assertTrue(result)

        self.current_time = self.db_primary_root_node.sh(
            'date \'+%Y-%m-%d %H:%M:%S\'').result()
        self.current_local_zone_str = self.db_primary_root_node.sh(
            'ls -l /etc/localtime').result()
        self.log.info('before dst. cache time is {}, {}.'.format(
            self.current_time, self.current_local_zone_str))

    def test_ddl_database(self):
        self.log.info('------------------1.创建数据库-------------------')
        sql = f'drop database if exists {self.dbname};' \
            f'create database {self.dbname};'
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS_MSG, result)

        self.log.info('------------------2.创建表空间-------------------')
        sql = f"create tablespace {self.dbspace} " \
            f"RELATIVE LOCATION '{self.dbspace}';"
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_TBLSPACE_SUCCESS_MSG, result)

        self.log.info('---------3、设置操作系统时区为new_york--------')
        cmd = f'cp {macro.DB_INSTANCE_PATH}/postgresql.conf ' \
            f'{macro.DB_INSTANCE_PATH}/postgresql.conf.timezone;' \
            f'echo "timezone=America/New_York" >> ' \
            f'{macro.DB_INSTANCE_PATH}/postgresql.conf'
        self.db_primary_db_user.sh(cmd)
        result = self.commonshpri.reloadDbConfig()
        self.log.info(result)
        self.assertIn(self.constant.RELOAD_SUCCESS_MSG, result)

        self.log.info('--------4、设置操作系统时间为2020-03-08凌晨01:58------')
        zonecmd = ln_sf_cmd.format(zone=new_york_local)
        self.log.info(zonecmd)
        result = self.db_primary_root_node.sh(zonecmd).result()
        self.log.info(result)
        self.log.info("设置操作系统时间为 03/08/2020 01:59:55(3月份第二个周日，即将开始夏令时)")
        datecmd = 'date -s \'03/08/2020 01:59:55\''
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(result)

        self.log.info('-------------------5、反复修改数据库100次-----------------')
        for i in range(100):
            self.log.info(f'============round:{i}============')
            sql = f"alter database {self.dbname} " \
                f"SET TABLESPACE  {self.dbspace};"
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn('ALTER', result)
            sql = f"alter database {self.dbname} SET TABLESPACE  pg_default;"
            result = self.commonshpri.executDbSql(sql)
            self.log.info(result)
            self.assertIn('ALTER', result)

        time.sleep(10)
        self.log.info("--------数据库查询select now()---------")
        result = self.db_primary_root_node.sh('date').result()
        self.log.info(result)
        result = self.commonshpri.executDbSql('select now();')
        self.log.info(result)
        self.assertTrue(result.find("2020-03-08 03") > -1)

    def tearDown(self):
        self.log.info('-------------------------环境清理---------------------')
        self.log.info("--------------------恢复时间---------------------")
        cmd = f'cp {macro.DB_INSTANCE_PATH}/postgresql.conf.timezone' \
            f' {macro.DB_INSTANCE_PATH}/postgresql.conf; '
        self.db_primary_db_user.sh(cmd)
        result = self.commonshpri.reloadDbConfig()
        self.log.info(result)

        recover_timezone = self.current_local_zone_str.split('->')[1]
        zonecmd = ln_sf_cmd.format(zone=recover_timezone)
        self.log.info('recover: ' + zonecmd)
        result = self.db_primary_root_node.sh(zonecmd).result()
        self.log.info(result)

        current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        datecmd = 'date -s \'{}\''.format(current_time)
        self.log.info('recover: ' + datecmd)
        result = self.db_primary_root_node.sh(datecmd).result()
        self.log.info(result)

        self.log.info('-------------------删除数据库-----------------')
        result = self.commonshpri.executDbSql(
            f'drop database if exists {self.dbname};')
        self.log.info(result)

        self.log.info('-------------------删除表空间-----------------')
        result = self.commonshpri.executDbSql(
            f'drop tablespace if exists {self.dbspace};')
        self.log.info(result)
        self.log.info('-----Opengauss_Reliability_Dbsys_Case237.py 执行结束---')
